import { defineStore } from "pinia";
import { ref } from "vue";
import { userGetInfoService } from "@/api/user";
import { constanRouter, asnycRoute, anyRoute } from "@/router/routes";
import router from "@/router";
import { userLoginService } from "@/api/user";
import { SET_TOKEN, REMOVE_TOKEN } from "@/utils/token";
import cloneDeep from "lodash/cloneDeep";
import { reqLogout } from "@/api/user";
let dynamicRoutes = [];
// 用户模块
export const useUserStore = defineStore("big-user", () => {
  let menuRouter = ref(constanRouter);
  let user = ref({});
  const buttons = ref([]);

  const userlogout = async () => {
    let res = await reqLogout();
    if (res.code === 0) {
      user.value = {};
      REMOVE_TOKEN();
      dynamicRoutes.forEach((route) => {
        if (route.name) {
          router.removeRoute(route.name);
        }
      });

      return "ok";
    } else {
      return Promise.reject(res.message);
    }
  };
  // 过滤异步路由
  const filterAsyncRoute = (asnycRoute, routes) => {
    return asnycRoute
      .filter((item) => {
        if (routes.includes(item.name)) {
          // 递归过滤子路由
          if (item.children && item.children.length > 0) {
            item.children = filterAsyncRoute(item.children, routes);
          }
          return true;
        }
      })
      .sort((a, b) => {
        // 根据后端返回的路由顺序进行排序
        return routes.indexOf(a.name) - routes.indexOf(b.name);
      });
  };

  const userLogin = async (data) => {
    console.log(data);
    let { code, result = {} } = await userLoginService(data);
    console.log(result);

    if (code === 0) {
      SET_TOKEN(result);
      return "ok";
    } else {
      return Promise.reject(new Error(result.message));
    }
  };

  const userInfo = async () => {
    let { code, result = {} } = await userGetInfoService();
    if (code === 0) {
      user.value = { ...result.userInfo, roles: result.roles };
      buttons.value = result.buttons;

      // 异步路由 - 根据后端返回的顺序进行过滤和排序
      const userAsyncRoute = filterAsyncRoute(cloneDeep(asnycRoute), [
        ...result.routes,
      ]);

      //菜单需要的数据整理完毕
      menuRouter.value = [...constanRouter, ...userAsyncRoute];

      dynamicRoutes = [...userAsyncRoute, ...anyRoute]; // 记录动态添加的路由
      //目前路由器管理的只有常量路由:用户计算完毕异步路由、任意路由动态追加
      dynamicRoutes.forEach((route) => {
        router.addRoute(route); // 动态添加路由
      });

      return "ok";
    } else {
      return Promise.reject("获取用户信息失败");
    }
  };
  return {
    userLogin,
    userlogout,
    userInfo,
    menuRouter,
    user,
    buttons,
  };
});
